package com.acheli.registry.event;

import com.acheli.registry.network.ACHMessages;
import com.acheli.registry.network.packet.EntityJoinC2SPacket;
import com.acheli.registry.network.packet.EntityLeaveC2SPacket;
import com.acheli.rideable.entites.RideableEntity;
import net.minecraft.world.entity.Entity;
import net.minecraftforge.event.entity.EntityJoinLevelEvent;
import net.minecraftforge.event.entity.EntityLeaveLevelEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class CustomDynamicEntityPool {
//    public static List<RideableEntity> rideableEntityList = new ArrayList<>();
    // 修改键类型为 Class<? extends Entity> 以支持所有实体子类
    public static HashMap<Class<? extends Entity>, List<Entity>> entityMap = new HashMap<>();

    public static void join(Entity entity) {
//        // 处理 RideableEntity
//        if (entity instanceof RideableEntity rideable) {
//            rideableEntityList.add(rideable);
//        }

        // 处理所有实体到 entityMap
        Class<? extends Entity> entityClass = entity.getClass();
        entityMap.computeIfAbsent(entityClass, k -> new ArrayList<>()).add(entity);
    }

    public static void leave(Entity entity) {
//        // 处理 RideableEntity
//        if (entity instanceof RideableEntity rideable) {
//            rideableEntityList.remove(rideable);
//        }

        // 处理所有实体从 entityMap 移除
        Class<? extends Entity> entityClass = entity.getClass();
        List<Entity> entities = entityMap.get(entityClass);
        if (entities != null) {
            entities.remove(entity);
            // 若该类的实体列表为空，清理条目
            if (entities.isEmpty()) {
                entityMap.remove(entityClass);
            }
        }
    }

    public static void joinEvent(EntityJoinLevelEvent event) {
        Entity entity = event.getEntity();
        join(entity);
        ACHMessages.sendToServer(new EntityJoinC2SPacket(entity.getId()));
    }

    public static void leaveEvent(EntityLeaveLevelEvent event) {
        Entity entity = event.getEntity();
        leave(entity);
        ACHMessages.sendToServer(new EntityLeaveC2SPacket(entity.getId()));
    }
}